<template>
  <div class="tutor-assistant">
    <!-- 顶部导航栏 -->
    <header class="assistant-header">
      <div class="header-left">
        <div class="back-btn" @click="goBack">
          <Icon name="ArrowLeft" :size="24" />
        </div>
        <div class="header-title">
          <h2 class="page-title">智能答疑助手</h2>
          <span class="status-dot"></span>
        </div>
      </div>
      <div class="header-right">
        <div class="theme-toggle" @click="toggleTheme">
          <Icon :name="isDark ? 'Sun' : 'Moon'" :size="20" />
        </div>
      </div>
    </header>

    <!-- 对话区域 -->
    <main class="chat-container">
      <div class="messages-wrapper" ref="messagesWrapper">
        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="ai-avatar-large">
            <div class="avatar-core"></div>
            <div class="avatar-glow"></div>
            <div class="avatar-eyes">
              <span></span><span></span>
            </div>
          </div>
          <h3>我是您的智能助教</h3>
          <p>您可以上传题目图片，或直接告诉我您的问题</p>
          
          <div class="feature-grid">
            <div class="feature-item">
              <div class="feature-icon blue">
                <Icon name="Camera" :size="20" />
              </div>
              <span>拍照搜题</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon purple">
                <Icon name="BookOpen" :size="20" />
              </div>
              <span>分步讲解</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon green">
                <Icon name="Lightbulb" :size="20" />
              </div>
              <span>举一反三</span>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          class="message-item-wrapper"
        >
          <McBubble
            :align="message.from === 'user' ? 'right' : 'left'"
            :avatarConfig="message.from === 'user' ? userAvatarConfig : aiAvatarConfig"
            :variant="'filled'"
          >
            <template #default>
              <div class="bubble-content">
                <!-- Markdown 内容（支持公式） -->
                <div v-if="message.text" class="message-text">
                  <mc-markdown-card v-if="message.from === 'assistant'" :content="message.text" :mdPlugins="mdPlugins" />
                  <span v-else>{{ message.text }}</span>
                </div>
                
                <!-- 文件列表 -->
                <mc-file-list 
                  v-if="message.files && message.files.length > 0"
                  :fileItems="message.files"
                  context="dialog"
                  @preview="handlePreview"
                />
              </div>
            </template>
            
            <!-- 快捷提问（底部区域） -->
            <template #bottom v-if="index === messages.length - 1 && message.from === 'assistant'">
              <div class="prompt-wrapper">
                <McPrompt 
                  :list="promptList" 
                  :direction="'horizontal'"
                  :variant="'bordered'"
                  @click="handlePromptClick"
                />
              </div>
            </template>
          </McBubble>
        </div>

        <!-- 加载中 -->
        <div v-if="isLoading" class="message-item-wrapper">
          <McBubble
            :align="'left'"
            :avatarConfig="aiAvatarConfig"
            :loading="true"
            :variant="'filled'"
          >
            <template #loadingTpl>
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </template>
          </McBubble>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-wrapper">
          <mc-input 
            v-model="inputValue" 
            @submit="handleSubmit"
            @send="handleSubmit"
            placeholder="输入问题或上传题目图片..."
            sendBtnVariant="simple"
            class="custom-mc-input"
          >
            <template #head>
              <div class="appendix-wrap" v-if="uploadedFiles.length > 0">
                <div class="appendix-item" v-for="file in uploadedFiles" :key="file.id">
                  <span>{{ file.name }}</span>
                  <div class="close-icon" @click="removeFile(file.id)">
                    <Icon name="X" :size="14" />
                  </div>
                </div>
              </div>
            </template>
            
            <template #extra>
              <div class="input-foot">
                <div class="input-foot-left">
                  <div class="tool-btn">
                    <Icon name="AtSign" :size="16" />
                    <span>智能体</span>
                  </div>
                  <div class="tool-btn" @click="triggerFileUpload">
                    <Icon name="Paperclip" :size="16" />
                    <span>上传题目</span>
                  </div>
                </div>
              </div>
            </template>
          </mc-input>
        </div>
      </div>
    </main>

    <!-- 图片预览模态框 -->
    <Modal 
      v-model:visible="previewModalVisible" 
      :title="previewFile?.name || '图片预览'"
      width="800px"
    >
      <img 
        v-if="previewFile" 
        :src="previewFile.url" 
        alt="预览"
        style="max-width: 100%; max-height: 80vh; object-fit: contain; display: block; margin: 0 auto;"
      />
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Icon from '@/components/icons/Icon.vue'
import Modal from '@/components/Modal.vue'
import { katex } from '@mdit/plugin-katex'
import { 
  McInput, 
  McBubble, 
  McFileList, 
  McMarkdownCard,
  McPrompt
} from '@matechat/core'

const router = useRouter()
const previewModalVisible = ref(false)
const previewFile = ref<FileItem | null>(null)

interface Message {
  from: 'user' | 'assistant'
  text: string
  files?: FileItem[]
}

interface FileItem {
  id: string
  name: string
  url: string
  size: number
  type: string
}

const messages = ref<Message[]>([])
const inputValue = ref('')
const uploadedFiles = ref<FileItem[]>([])
const isLoading = ref(false)
const isDark = ref(false)
const messagesWrapper = ref<HTMLElement | null>(null)

// 配置 Markdown 插件支持公式
const mdPlugins = ref([
  {
    plugin: katex,
    opt: {}
  }
])

// 快捷提示按钮配置
const promptList = [
  {
    value: 're-explain',
    label: '重新讲解一遍',
    desc: '重新详细讲解解题过程'
  },
  {
    value: 'next-step',
    label: '继续下一步',
    desc: '继续讲解下一步骤'
  },
  {
    value: 'related-knowledge',
    label: '相关知识点',
    desc: '了解相关数学知识点'
  }
]

// 头像配置 - 使用扁平简洁的头像
const aiAvatarConfig = {
  imgSrc: 'https://matechat.gitcode.com/logo.svg',
  displayName: '智能助教'
}

const userAvatarConfig = {
  imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg',
  displayName: '我'
}

// 模拟 AI 回复
const generateAIResponse = async (userMessage: string, files: FileItem[]): Promise<{ text: string, files?: FileItem[] }> => {
  // 模拟 API 调用延迟
  await new Promise(resolve => setTimeout(resolve, 1500))
  
  if (files.length > 0) {
    // 模拟返回一个分析报告文件
    const reportFile: FileItem = {
      id: Date.now().toString(),
      name: '题目分析报告.pdf',
      url: '#',
      size: 1024 * 1024 * 1.5,
      type: 'application/pdf'
    }

    return {
      text: `**题目分析**：我已经识别了你上传的题目图片。

**解题步骤**：

1. 首先分析题目条件，确定考察的知识点
2. 根据已知条件，建立相应的数学模型
3. 运用相关公式或定理进行求解
4. 验证答案的合理性

**示例计算**：
- 设变量 $x$，根据题意：$f(x) = x^2 - 4x + 3$
- 配方得：$f(x) = (x-2)^2 - 1$
- 当 $x = 2$ 时，取得最小值 $-1$

> ⚠️ **易错点**：注意检查定义域，避免遗漏边界情况。

为您生成了一份详细的分析报告，请查看附件。`,
      files: [reportFile]
    }
  }
  
  return {
    text: `**回答**：${userMessage}

这是一个很好的问题！让我为你详细解答：

**核心思路**：
1. 理解问题的本质
2. 分析关键条件
3. 选择合适的解题方法
4. 逐步推理得出结论

**详细说明**：
根据你提出的问题，我建议从以下几个方面来思考...

**相关公式**：

行内公式：$E = mc^2$，其中 $m$ 是质量，$c$ 是光速。

块级公式：
$$
\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}
$$

二次方程求根公式：
$$
x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}
$$

需要我进一步解释吗？`
  }
}

const handleSubmit = async (event?: any) => {
  // 阻止默认行为（如果有）
  if (event && typeof event.preventDefault === 'function') {
    event.preventDefault()
  }
  
  // 阻止事件冒泡
  if (event && typeof event.stopPropagation === 'function') {
    event.stopPropagation()
  }

  // 检查是否有输入内容（文字是必须的，图片是可选的）
  const userText = inputValue.value.trim()
  // if (!userText) {
  //   console.log('No input text')
  //   return
  // }

  console.log('Submitting:', { text: userText, files: uploadedFiles.value.length })
  
  // 确保响应式更新
  await nextTick()

  // 保存当前输入和文件（在清空前）
  const currentFiles = [...uploadedFiles.value]

  // 添加用户消息（文字是必须的，文件是可选的）
  const userMessage: Message = {
    from: 'user',
    text: userText,
    files: currentFiles.length > 0 ? currentFiles : undefined
  }
  messages.value.push(userMessage)
  console.log('User message added:', userMessage)
  console.log('Messages array length:', messages.value.length)
  
  // 立即触发响应式更新和滚动
  await nextTick()
  scrollToBottom()

  // 清空输入和文件
  inputValue.value = ''
  uploadedFiles.value = []

  // 显示加载状态
  isLoading.value = true
  await nextTick()
  scrollToBottom()

  try {
    // 生成 AI 回复
    const aiResponse = await generateAIResponse(userText, currentFiles)
    
    console.log('AI Response:', aiResponse)
    
    // 添加 AI 消息
    messages.value.push({
      from: 'assistant',
      text: aiResponse.text,
      files: aiResponse.files
    })
  } catch (error) {
    console.error('Error generating response:', error)
    messages.value.push({
      from: 'assistant',
      text: '抱歉，处理你的问题时出现了错误，请稍后再试。'
    })
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

const handlePromptClick = (item: any) => {
  let promptText = ''
  
  switch (item.value) {
    case 're-explain':
      promptText = '请重新详细讲解一遍这道题的解题过程'
      break
    case 'next-step':
      promptText = '请继续讲解下一步骤'
      break
    case 'related-knowledge':
      promptText = '这道题涉及哪些相关知识点？请详细说明'
      break
    default:
      promptText = item.label || ''
  }
  
  if (promptText) {
    inputValue.value = promptText
    handleSubmit()
  }
}

const removeFile = (fileId: string) => {
  uploadedFiles.value = uploadedFiles.value.filter((f: FileItem) => f.id !== fileId)
}

const handlePreview = (file: FileItem) => {
  previewFile.value = file
  previewModalVisible.value = true
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesWrapper.value) {
      messagesWrapper.value.scrollTop = messagesWrapper.value.scrollHeight
    }
  })
}

const goBack = () => {
  router.push('/')
}

const toggleTheme = () => {
  isDark.value = !isDark.value
  // 这里可以集成主题切换逻辑
  document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')
}

// 处理文件上传
const handleFiles = (files: FileList) => {
  Array.from(files).forEach(file => {
    if (file.type.startsWith('image/')) {
      const reader = new FileReader()
      reader.onload = (event: ProgressEvent<FileReader>) => {
        const fileItem: FileItem = {
          id: Date.now().toString() + Math.random(),
          name: file.name,
          url: event.target?.result as string,
          size: file.size,
          type: file.type
        }
        uploadedFiles.value.push(fileItem)
      }
      reader.readAsDataURL(file)
    }
  })
}

const triggerFileUpload = () => {
  if (window._fileInput) {
    window._fileInput.click()
  }
}

// 扩展 Window 接口
declare global {
  interface Window {
    _fileInput: HTMLInputElement
  }
}

// 文件上传处理
onMounted(() => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = true
  input.style.display = 'none'
  
  input.addEventListener('change', (e) => {
    const files = (e.target as HTMLInputElement).files
    if (files) {
      handleFiles(files)
    }
    // 清除 input value 允许重复上传同一文件
    input.value = ''
  })
  
  // 暴露给上传按钮使用
  window._fileInput = input
  
  // 监听拖拽上传
  const dropZone = document.querySelector('.input-area')
  if (dropZone) {
    dropZone.addEventListener('dragover', (e: Event) => {
      e.preventDefault()
    })
    
    dropZone.addEventListener('drop', (e: Event) => {
      e.preventDefault()
      const dragEvent = e as DragEvent
      const files = dragEvent.dataTransfer?.files
      if (files) {
        handleFiles(files)
      }
    })
  }
})
</script>

<style scoped>
@import 'katex/dist/katex.min.css';
.tutor-assistant {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #f5f7fa 0%, #ffffff 100%);
}

.assistant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.02);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  color: #4b5563;
}

.back-btn:hover {
  background: #f3f4f6;
  color: #1f2937;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #10b981;
  border-radius: 50%;
  box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}

.theme-toggle {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  color: #4b5563;
}

.theme-toggle:hover {
  background: #f3f4f6;
  color: #f59e0b;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: white;
}

.messages-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 24px 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 600px;
  margin: 0 auto;
}

.ai-avatar-large {
  position: relative;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}

.ai-avatar-large .avatar-core {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, #60a5fa, #2563eb);
  box-shadow: 
    0 0 15px rgba(96, 165, 250, 0.4),
    0 0 30px rgba(96, 165, 250, 0.3),
    0 0 45px rgba(96, 165, 250, 0.2),
    0 4px 12px rgba(37, 99, 235, 0.4);
  position: relative;
  z-index: 2;
}

.ai-avatar-large .avatar-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 120%;
  height: 120%;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.2) 0%, rgba(59, 130, 246, 0) 70%);
  border-radius: 50%;
  animation: pulse 2s ease-in-out infinite;
}

.ai-avatar-large .avatar-eyes {
  position: absolute;
  z-index: 3;
  display: flex;
  gap: 6px;
  top: 40%;
  left: 50%;
  transform: translateX(-50%);
}

.ai-avatar-large .avatar-eyes span {
  width: 8px;
  height: 12px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 0 4px rgba(255, 255, 255, 0.8);
}

.welcome-message h3 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 12px;
}

.welcome-message p {
  color: #6b7280;
  font-size: 16px;
  margin-bottom: 40px;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  width: 100%;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
  cursor: pointer;
}

.feature-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.feature-item .feature-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.feature-icon.blue { background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%); }
.feature-icon.purple { background: linear-gradient(135deg, #a78bfa 0%, #8b5cf6 100%); }
.feature-icon.green { background: linear-gradient(135deg, #34d399 0%, #10b981 100%); }

.feature-item span {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

/* 消息样式 */
.message-item-wrapper {
  padding: 0 24px;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  margin-bottom: 16px;
}

.bubble-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-text {
  white-space: pre-wrap;
  word-break: break-word;
}

/* 优化 McBubble 样式 */
.message-item-wrapper :deep(.mc-bubble) {
  max-width: 80%;
}

.message-item-wrapper :deep(.mc-bubble[align="right"]) {
  margin-left: auto;
}

.message-item-wrapper :deep(.mc-bubble[align="left"]) {
  margin-right: auto;
}

/* 用户消息气泡样式 */
.message-item-wrapper :deep(.mc-bubble[align="right"] .mc-bubble-content) {
  background: #3b82f6;
  color: white;
}

.message-item-wrapper :deep(.mc-bubble[align="right"] .mc-bubble-content .file-list-item) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
}

.message-item-wrapper :deep(.mc-bubble[align="right"] .mc-bubble-content .file-name),
.message-item-wrapper :deep(.mc-bubble[align="right"] .mc-bubble-content .file-size) {
  color: rgba(255, 255, 255, 0.9);
}

/* AI 消息气泡样式 */
.message-item-wrapper :deep(.mc-bubble[align="left"] .mc-bubble-content) {
  background: white;
  color: #1f2937;
}

/* AI 消息中的文件列表背景改为白色 */
.message-item-wrapper :deep(.mc-bubble[align="left"] .mc-bubble-content .file-list-item) {
  background: white;
  border: 1px solid #e5e7eb;
  color: #1f2937;
}

.message-item-wrapper :deep(.mc-bubble[align="left"] .mc-bubble-content .file-name),
.message-item-wrapper :deep(.mc-bubble[align="left"] .mc-bubble-content .file-size) {
  color: #1f2937;
}

/* 头像优化 - 扁平简洁样式 */
.message-item-wrapper :deep(.mc-bubble-avatar img) {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: none;
  box-shadow: none;
  background: transparent;
}

.prompt-wrapper {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f3f4f6;
}

.prompt-wrapper :deep(.mc-prompt) {
  width: 100%;
}

.prompt-wrapper :deep(.mc-prompt-item) {
  cursor: pointer;
  transition: all 0.2s;
}

.prompt-wrapper :deep(.mc-prompt-item:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 输入区域 */
.input-area {
  padding: 24px;
  background: white;
  border-top: 1px solid rgba(0, 0, 0, 0.04);
}

.input-wrapper {
  max-width: 1000px;
  margin: 0 auto;
}

/* 输入区域样式优化 */
.input-wrapper :deep(.mc-input) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.2s;
  background: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02);
}

.input-wrapper :deep(.mc-input:focus-within) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.input-wrapper :deep(textarea) {
  font-size: 15px;
  line-height: 1.6;
}

/* 隐藏 mc-input 组件自带的发送按钮 */
.input-wrapper :deep(.mc-input .mc-input-send),
.input-wrapper :deep(.mc-input button[type="submit"]),
.input-wrapper :deep(.mc-input .send-btn),
.input-wrapper :deep(.mc-input .mc-input-action) {
  display: none !important;
}

.input-foot {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 8px;
  width: 100%;
}

.input-foot-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.tool-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #6b7280;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s;
}

.tool-btn:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

.send-button {
  width: 36px;
  height: 36px;
  background: #2563eb;
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(37, 99, 235, 0.2);
  margin-left: auto;
}

.send-button:hover {
  background: #1d4ed8;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
}

.appendix-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 12px;
  border-bottom: 1px solid #f3f4f6;
}

.appendix-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  border-radius: 6px;
  background-color: #f3f4f6;
  font-size: 12px;
  color: #374151;
}

.close-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #6b7280;
  padding: 2px;
  border-radius: 4px;
  transition: all 0.2s;
  min-width: 16px;
  min-height: 16px;
}

.close-icon:hover {
  background: #e5e7eb;
  color: #ef4444;
}

.close-icon :deep(.icon) {
  display: block;
}

/* 动画 */
@keyframes pulse {
  0%, 100% { opacity: 0.5; transform: translate(-50%, -50%) scale(0.9); }
  50% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #9ca3af;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing {
  0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }
  30% { transform: translateY(-6px); opacity: 1; }
}
</style>